package com.yonyou.cyxdms.basedata.client.service.basedata;

import com.yonyou.cyx.framework.bean.dto.base.ClientInfoDTO;
import com.yonyou.cyx.framework.compent.redis.RedisClient;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.utils.common.CommonUtils;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyxdms.basedata.client.constants.BaseDataCommonConstants;
import com.yonyou.cyxdms.basedata.client.domains.vo.SeriesCacheVO;
import com.yonyou.cyxdms.basedata.client.feign.BaseDataCommonClient;
import com.yonyou.cyxdms.basedata.client.util.ConditionMapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.List;
import java.util.Map;

/**
 * 车系信息
 *
 * @author: renwd
 * @since: 2018/11/29
 * @updateDate:
 * @updateRemark:
 * @version:1.0 Copyright: Copyright (c) 2018
 */
@Service
public class BaseCommonSeriesServiceImpl implements BaseCommonSeriesService {

    private final Logger logger = LoggerFactory.getLogger(BaseCommonSeriesServiceImpl.class);

    @Autowired
    private BaseDataCommonClient baseDataCommonClient;

    @Autowired
    private RedisClient redisClient;

    /**
     * 根据车系id查询车系信息
     *
     * @param serialId
     * @return com.yonyou.cyxdms.basedata.client.domains.vo.SeriesCacheVO
     * @author renwd
     * @since 2019/9/10
     */
    @Override
    public SeriesCacheVO getValueBySeriesId(String serialId) {
        ClientInfoDTO loginInfoDto = ApplicationContextHelper.getBeanByType(ClientInfoDTO.class);
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.SERIAL_CACHE_SERIESID, loginInfoDto.getAppId());
        Object serialData = redisClient.hget(messageFormat, serialId);
        if (null == serialData) {
            // 重新加载这个id值的数据
            loadValueIfNotExists(ConditionMapUtils.conditionMap(loginInfoDto.getAppId(), null), messageFormat);
            Object redisSerialData = redisClient.hget(messageFormat, serialId);
            if (null == redisSerialData) {
                return null;
            }
            return JSONUtil.jsonToObj(JSONUtil.objectToJson(redisSerialData), SeriesCacheVO.class);
        } else {
            return JSONUtil.jsonToObj(JSONUtil.objectToJson(serialData), SeriesCacheVO.class);
        }
    }

    /**
     * 查询数据
     *
     * @param queryByMap 查询条件
     * @author renwd
     * @since 2018/11/30
     */
    private void loadValueIfNotExists(Map<String, Object> queryByMap, String messageFormat) {
        List<SeriesCacheVO> seriesDtoResponse = baseDataCommonClient.querySeriesBySql(queryByMap).getData();
        logger.info("feign查询Series信息:{}", seriesDtoResponse);

        if (!CommonUtils.isNullOrEmpty(seriesDtoResponse)) {
            seriesDtoResponse.stream().forEach(seriesCacheDto -> initOneValue(seriesCacheDto, messageFormat));
        }
    }

    /**
     * 数据放置redis
     *
     * @param seriesCache
     * @author renwd
     * @since 2018/11/30
     */
    private void initOneValue(SeriesCacheVO seriesCache, String key) {
        redisClient.hsetExpire(key, String.valueOf(seriesCache.getSeriesId()), JSONUtil.objectToJson(seriesCache), BaseDataCommonConstants.EXPIRE_TIME_ONE_DAY);
    }

    /**
     * @description：根据车系名称模糊查询
     * @author     ：quankk
     * @date       ：Created in 2019/1/15 11:23
     * @modified By：
     */
    @Override
    public List<SeriesCacheVO> seriesBySeriesName(String appId, String seriesName) {
        return baseDataCommonClient.seriesBySeriesName(appId, seriesName).getData();
    }

    @Override
    public List<SeriesCacheVO> allSeries() {
        return baseDataCommonClient.allSeries().getData();
    }

    /**
     * 查询租户下的经销商下的所有车系
     *
     * @return java.util.List<com.yonyou.cyxdms.basedata.client.domains.vo.SeriesCacheVO>
     * @author renwd
     * @since 2019/9/10
     */
    @Override
    public List<SeriesCacheVO> listAllSeries() {
        ClientInfoDTO loginInfoDto = ApplicationContextHelper.getBeanByType(ClientInfoDTO.class);
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.SERIAL_CACHE_SERIES_ALL, loginInfoDto.getAppId(), loginInfoDto.getOwnerCode());
        Object serialData = redisClient.get(messageFormat);
        if (null == serialData) {
            // 重新加载这个id值的数据
            List<SeriesCacheVO> seriesDtoResponse = baseDataCommonClient.querySeriesBySql(ConditionMapUtils.conditionMap(loginInfoDto.getAppId(), loginInfoDto.getOwnerCode())).getData();
            logger.info("feign查询Series信息:{}", seriesDtoResponse);

            if (!CommonUtils.isNullOrEmpty(seriesDtoResponse)) {
                redisClient.set(messageFormat, JSONUtil.objectToJson(seriesDtoResponse), BaseDataCommonConstants.EXPIRE_TIME_ONE_DAY);
            }

            Object redisSerialData = redisClient.get(messageFormat);
            if (null == redisSerialData) {
                return null;
            }
            return JSONUtil.jsonToList(JSONUtil.objectToJson(redisSerialData), SeriesCacheVO.class);
        } else {
            return JSONUtil.jsonToList(JSONUtil.objectToJson(serialData), SeriesCacheVO.class);
        }
    }

    /**
     * @author ：maxingjian
     * @date ：2019/8/29 10:24
     * @description：通过品牌ID查询车系
     */
    @Override
    public List<SeriesCacheVO> getSeriesByBrandId(String brandId) {
        return  baseDataCommonClient.getSeriesByBrandId(brandId).getData();
    }

    @Override
    public List<SeriesCacheVO> getAllSeriesByAppId(String appId) {
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.SERIAL_CACHE_SERIES_APPID_ALL, appId);
        //ClientInfoDTO loginInfoDto = ApplicationContextHelper.getBeanByType(ClientInfoDTO.class);
        Object seriesDTO = redisClient.get(messageFormat);
        if (null == seriesDTO) {
            // 查询所有数据

            List<SeriesCacheVO> seriesDtoResponse = baseDataCommonClient.getAllSeriesByAppId(appId).getData();
            logger.info("feign查询series信息:{}", seriesDtoResponse);
            if (!CommonUtils.isNullOrEmpty(seriesDtoResponse)) {
                redisClient.set(messageFormat, JSONUtil.objectToJson(seriesDtoResponse),
                        BaseDataCommonConstants.EXPIRE_TIME_ONE_DAY);
            }
            Object redisSeriesDto = redisClient.get(messageFormat);
            if (null == redisSeriesDto) {
                return null;
            }
            return JSONUtil.jsonToList(JSONUtil.objectToJson(redisSeriesDto), SeriesCacheVO.class);
        } else {
            return JSONUtil.jsonToList(JSONUtil.objectToJson(seriesDTO), SeriesCacheVO.class);
        }
    }

}
